package com.haojiang.mh.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import androidx.appcompat.widget.AppCompatImageView;

/**
 * 连接设备Loading
 */
public class RotateSelfImageView extends AppCompatImageView {

    Animation animation;

    public RotateSelfImageView(Context context) {
        this(context, null);
    }

    public RotateSelfImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RotateSelfImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (getAnimation() != null) {
            animation = getAnimation();
        } else {
            animation = createAnimation();
            setAnimation(animation);
        }
        animation.start();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (animation != null) {
            animation.cancel();
            animation = null;
        }
        clearAnimation();
    }

    private Animation createAnimation() {
        RotateAnimation rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f);
        rotateAnimation.setDuration(1000);
        rotateAnimation.setInterpolator(new LinearInterpolator());
        rotateAnimation.setRepeatCount(Animation.INFINITE);
        rotateAnimation.setRepeatMode(Animation.RESTART);
        return rotateAnimation;
    }
}
